package com.neusoft.elm.framework;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 前端控制器
 * 拦截url格式：/控制器类名/控制器方法名
 */
@WebServlet("/")
public class DispatcherServlet extends HttpServlet {

    /**
     * 处理Post请求
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //中文编码处理
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //获取客户端请求路径
        String path = request.getServletPath();

        //解析Controller的类名和方法名
        String className = path.substring(1,path.lastIndexOf("/"));
        String methodName = path.substring(path.lastIndexOf("/")+1);


        PrintWriter out = null;

        //根据请求，将其分发给相应的业务处理器
        try{
            //由Controller类全名获取此类全部信息
            Class clazz = Class.forName("com.neusoft.elm.controller."+className);
            //创建Controller类对象
            Object controller = clazz.newInstance();
            //获取Controller类对象中的方法
            Method method = clazz.getMethod(methodName,new Class[]{HttpServletRequest.class});
            //调用获取方法
            Object result = method.invoke(controller,new Object[]{request});

            //获取向用户端响应的输出流
            out = response.getWriter();
            ObjectMapper om = new ObjectMapper();
            //向客户端响应JSON数据
            out.print(om.writeValueAsString(result));

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("DispatcherServlet信息：请求url："+path);
            System.out.println("DispatcherServlet信息：类名："+className+"\t方法名："+methodName);
        }finally {
            out.close();
        }
    }


    /**
     * 处理Get请求
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        doPost(request,response);
    }
}
